// server.js
const http2 = require('http2');
const fs = require('fs');

// 加载SSL证书
const serverOptions = {
    // key: fs.readFileSync('/root/pangolin-npm/https/server.key'),
    // cert: fs.readFileSync('/root/pangolin-npm/https/server.crt')
    key: fs.readFileSync('/Users/fly/Documents/https/server.key'),
    cert: fs.readFileSync('/Users/fly/Documents/https/server.crt')
};

// 创建HTTP/2服务器
const server = http2.createSecureServer(serverOptions);

server.on('stream', (stream, headers) => {
    let data = '';

    // 监听数据事件
    stream.on('data', chunk => {
        console.log('Received data from client:', chunk.toString() + '\n');
        data += chunk;
    });

    // 监听请求结束事件
    stream.on('end', () => {
        console.log('Received data from client:', data);
        // 这里服务器可以主动向客户端发送数据
        stream.write('Server message at ' + new Date().toISOString());
        //stream.end();
    });

    // 监听错误事件
    stream.on('error', (err) => {
        console.error('Stream error:', err);
    });

    // 模拟服务器定时向客户端发送数据
    const interval = setInterval(() => {
        console.log('Periodic server message')
        stream.write('Periodic server message at ' + new Date().toISOString());
    }, 5000);

    // stream.on('close', () => {
    //     clearInterval(interval);
    // });
});

// 服务器监听端口
server.listen(8443, () => {
    console.log('HTTP/2 server is listening on port 8443');
});
